package com.villaday.idf.activity;


import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.appcompat.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.villaday.idf.R;
import com.villaday.idf.adapter.CustomerBehaviorAdapter;
import com.villaday.idf.base.AbsRecyclerViewAdapter;
import com.villaday.idf.base.BaseActivity;
import com.villaday.idf.base.OnAdapterCallbackListener;
import com.villaday.idf.custom.LoadingDialog;
import com.villaday.idf.custom.DividerItemDecoration.RVItemDecoration;
import com.villaday.idf.model.VipsMemberActions;
import com.villaday.idf.util.Constant;
import com.villaday.idf.util.LogeUtil;
import com.villaday.idf.util.OkHttpUtil;
import com.villaday.idf.util.PhoneUtil;
import com.villaday.idf.util.ToolBarUtil;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * 客户行为
 */
public class CustomerBehaviorActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener, AbsRecyclerViewAdapter.OnItemClickListener, OnAdapterCallbackListener, OkHttpUtil.OnDataListener {

    @BindView(R.id.ll_select_layout)
    public LinearLayout llSelectLayout;
    @BindView(R.id.toolbar_icon)
    Toolbar toolbar;
    @BindView(R.id.rv)
    RecyclerView rv;
    @BindView(R.id.srl)
    SwipeRefreshLayout srl;

    @BindView(R.id.tv_install_app)
    public TextView tvInstall;
    @BindView(R.id.tv_inquire_start_time)
    public TextView tvStartTime;
    @BindView(R.id.tv_inquire_end_time)
    public TextView tvEndTime;

    Unbinder unbinder;
    private LoadingDialog loadingDialog;
    private Gson gson = new GsonBuilder().create();

    private int pageNo = 1;
    private int nextIndex = 1;
    private int pageSize = 20;
    List<VipsMemberActions.BodyBean.ListBean> data = new ArrayList();
    private CustomerBehaviorAdapter customerBehaviorAdapter;

    private int downloadApp = 0;
    private String beginDateTime = "";
    private String endDateTime = "";


    @Override
    protected int getViewResId() {
        return R.layout.activity_customer_behavior;
    }

    @Override
    protected void init() {
        llSelectLayout.setVisibility(View.VISIBLE);
        ToolBarUtil.init(toolbar, "客户行为", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });
        srl.setOnRefreshListener(this);
        rv.setLayoutManager(new LinearLayoutManager(this));
        customerBehaviorAdapter = new CustomerBehaviorAdapter(this, this);
        rv.setAdapter(customerBehaviorAdapter);

        rv.addItemDecoration(new RVItemDecoration(LinearLayout.VERTICAL, PhoneUtil.dp2px(this, 1), getResources().getColor(R.color.colorBg), PhoneUtil.dp2px(this, 8)));
        customerBehaviorAdapter.setOnItemClickListener(this);
 /*       View inflate = View.inflate(this, R.layout.item_head_income_details, null);
        customerBehaviorAdapter.addHeaderView(inflate);*/
        customerBehaviorAdapter.setEmptyView(R.layout.empty_tips_white);
        customerBehaviorAdapter.setEmptyTips(R.id.tv_emptyTips, "没有更多了");
    }

    @Override
    protected void loadData() {
        pageNo = 1;
        nextIndex = 1;
        getData();
    }

    private void getData() {
        LogeUtil.e("loge", "downloadApp==" + downloadApp + "  beginDateTime==" + beginDateTime + " endDateTime==" + endDateTime);
        Map<String, String> map = new HashMap<>();
        map.put("pageNo", pageNo + "");
        map.put("pageSize", pageSize + "");
        //map.put("downloadApp", downloadApp + "");
        if (downloadApp == 0) {
            map.put("memberType", -1 + "");//所有

        } else if (downloadApp == 1) {
            map.put("memberType", 0 + "");//粉丝

        } else {
            map.put("memberType", 1 + "");//下级会员

        }


        map.put("beginDateTime", beginDateTime);
        map.put("endDateTime", endDateTime);
        OkHttpUtil.getJSON(this, Constant.URL.vips_member_actions, map, this);
    }

    @Override
    public void onRefresh() {
        pageNo = 1;
        nextIndex = 1;
        getData();
    }

    //rv item 点击事件
    @Override
    public void onItemClick(View v, int position) {
/*        Intent intent = new Intent(this, FindDetailsActivity.class);
        intent.putExtra("topicId", data.get(position).getId());
        startActivity(intent);*/
    }

    @OnClick({R.id.tv_install_app, R.id.tv_inquire_start_time, R.id.tv_inquire_end_time, R.id.tv_select_btn})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_install_app: {  //安装App
                initInstallApp();
            }
            break;
            case R.id.tv_inquire_start_time: {  //开始时间
                initStartTime();
            }
            break;
            case R.id.tv_inquire_end_time: {  //结束时间
            }
            break;
            case R.id.tv_select_btn: {  //查询
                if (!TextUtils.isEmpty(tvStartTime.getText().toString().trim())) {
                    if (!TextUtils.isEmpty(tvEndTime.getText().toString().trim())) {
                        beginDateTime = tvStartTime.getText().toString() + " 00:00:00";
                        endDateTime = tvEndTime.getText().toString() + " 00:00:00";
                    }
                }
                loadData();

            }
            break;
        }

    }

    private void initInstallApp() {
        final ArrayList<String> list = new ArrayList<>();
//        list.add("全部");
        list.add("所有");
        list.add("粉丝");
        list.add("下级会员");


        OptionsPickerView<String> mOptionsPickerView = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                downloadApp = options1;
                String sex = list.get(options1);
                tvInstall.setText(sex);
                getData();
            }
        }).setCancelColor(getResources().getColor(R.color.colorRed))
                .setSubmitColor(getResources().getColor(R.color.colorRed)).build();
        // 设置数据
        mOptionsPickerView.setPicker(list);
        // 设置选项单位
        mOptionsPickerView.show();
    }


    private void initStartTime() {
        Calendar selectedDate = Calendar.getInstance();
        int year = selectedDate.get(Calendar.YEAR);    //获取年
        int month = selectedDate.get(Calendar.MONTH) + 1;   //获取月份，0表示1月份
        int day = selectedDate.get(Calendar.DAY_OF_MONTH);    //获取当前天数
        int first = selectedDate.getActualMinimum(selectedDate.DAY_OF_MONTH);    //获取本月最小天数
        int last = selectedDate.getActualMaximum(selectedDate.DAY_OF_MONTH);    //获取本月最大天数
        int time = selectedDate.get(Calendar.HOUR_OF_DAY);       //获取当前小时
        int min = selectedDate.get(Calendar.MINUTE);          //获取当前分钟
        int xx = selectedDate.get(Calendar.SECOND);          //获取当前秒
        LogeUtil.e("loge", "");
//        Calendar startDate = Calendar.getInstance();
//        startDate.set(2013, 0, 1);
        Calendar endDate = Calendar.getInstance();
        endDate.set(year, month - 1, day);
        //正确设置方式 原因：注意事项有说明


        TimePickerView pvTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
                tvStartTime.setText(format.format(date));
                initEndTime(format.format(date));
            }
        }).setType(new boolean[]{true, true, true, false, false, false})// 默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确定")//确认按钮文字
                .setContentTextSize(18) //滚轮文字大小
                .setTitleSize(18)//标题文字大小
                .setTitleText("请选择开始时间")//标题文字
                .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(false)//是否循环滚动
                .setTitleColor(getResources().getColor(R.color.colorRed))//标题文字颜色
                .setSubmitColor(getResources().getColor(R.color.colorRed))//确定按钮文字颜色
                .setCancelColor(getResources().getColor(R.color.colorRed))//取消按钮文字颜色
                .setTitleBgColor(getResources().getColor(R.color.colorGrayBg))//标题背景颜色 Night mode
                .setBgColor(getResources().getColor(R.color.colorWhite))//滚轮背景颜色 Night mode
                .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
                .setRangDate(null, endDate)//起始终止年月日设定
                .setLabel("年", "月", "日", "时", "分", "秒")//默认设置为年月日时分秒
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .isDialog(false)//是否显示为对话框样式
                .build();
        pvTime.show();
    }


    private void initEndTime(String date) {
        Calendar selectedDate = Calendar.getInstance();

        String[] var = date.split("-");
        Calendar startDate = Calendar.getInstance();
        startDate.set(Integer.parseInt(var[0]), Integer.parseInt(var[1]) - 1, Integer.parseInt(var[2]) - 1);
//        Calendar endDate = Calendar.getInstance();
//        endDate.set(year, month-1, day);
        //正确设置方式 原因：注意事项有说明


        TimePickerView pvTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
                tvEndTime.setText(format.format(date));
            }
        }).setType(new boolean[]{true, true, true, false, false, false})// 默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确定")//确认按钮文字
                .setContentTextSize(18) //滚轮文字大小
                .setTitleSize(18)//标题文字大小
                .setTitleText("请选择结束时间")//标题文字
                .setOutSideCancelable(false)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(false)//是否循环滚动
                .setTitleColor(getResources().getColor(R.color.colorRed))//标题文字颜色
                .setSubmitColor(getResources().getColor(R.color.colorRed))//确定按钮文字颜色
                .setCancelColor(getResources().getColor(R.color.colorRed))//取消按钮文字颜色
                .setTitleBgColor(getResources().getColor(R.color.colorGrayBg))//标题背景颜色 Night mode
                .setBgColor(getResources().getColor(R.color.colorWhite))//滚轮背景颜色 Night mode
                .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
                .setRangDate(startDate, selectedDate)//起始终止年月日设定
                .setLabel("年", "月", "日", "时", "分", "秒")//默认设置为年月日时分秒
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .isDialog(false)//是否显示为对话框样式
                .build();
        pvTime.show();
    }

    private void initAddress() {
      /*  pvOptions = new  OptionsPickerBuilder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3 ,View v) {
                //返回的分别是三个级别的选中位置
                String tx = options1Items.get(options1).getPickerViewText()
                        + options2Items.get(options1).get(option2)
                        + options3Items.get(options1).get(option2).get(options3).getPickerViewText();
                tvOptions.setText(tx);
            }
        }) .setOptionsSelectChangeListener(new OnOptionsSelectChangeListener() {
            @Override
            public void onOptionsSelectChanged(int options1, int options2, int options3) {
                String str = "options1: " + options1 + "\noptions2: " + options2 + "\noptions3: " + options3;
                Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT).show();
            }
        })
                .setSubmitText("确定")//确定按钮文字
                .setCancelText("取消")//取消按钮文字
                .setTitleText("城市选择")//标题
                .setSubCalSize(18)//确定和取消文字大小
                .setTitleSize(20)//标题文字大小
                .setTitleColor(Color.BLACK)//标题文字颜色
                .setSubmitColor(Color.BLUE)//确定按钮文字颜色
                .setCancelColor(Color.BLUE)//取消按钮文字颜色
                .setTitleBgColor(0xFF333333)//标题背景颜色 Night mode
                .setBgColor(0xFF000000)//滚轮背景颜色 Night mode
                .setContentTextSize(18)//滚轮文字大小
                .setLinkage(false)//设置是否联动，默认true
                .setLabels("省", "市", "区")//设置选择的三级单位
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setCyclic(false, false, false)//循环与否
                .setSelectOptions(1, 1, 1)  //设置默认选中项
                .setOutSideCancelable(false)//点击外部dismiss default true
                .isDialog(true)//是否显示为对话框样式
                .isRestoreItem(true)//切换时是否还原，设置默认选中第一项。
                .build();

        pvOptions.setPicker(options1Items, options2Items, options3Items);//添加数据源*/
    }


    @Override
    public void onCallback() {
        if (nextIndex == pageNo + 1) {
            pageNo++;
            getData();
        }
    }

    @Override
    public void onResponse(String url, String json) {
        if (Constant.URL.vips_member_actions.equals(url)) {
            LogeUtil.e("vips_member_actions", json);
            dismissLoading();
            VipsMemberActions recommendEntity = gson.fromJson(json, VipsMemberActions.class);
            removeLoadingItem();
            if (pageNo == 1) {
                data.clear();
            }

            if ("200".equals(recommendEntity.getCode())) {
                   /* if (pageNo == 1 && presellEntity.getBody().getRecomendList() != null && presellEntity.getBody().getRecomendList().getList() != null) {

                        dataHead.addAll(presellEntity.getBody().getRecomendList().getList());
                        homeListSaleHeadAdapter.setData(dataHead);
                    }*/
                data.addAll(recommendEntity.getBody().getList());
                if (recommendEntity.getBody().isHasNext()) {
                    data.add(new VipsMemberActions.BodyBean.ListBean(1));
                    nextIndex = pageNo + 1;

                } else {
                    addBaseLine();
                }

            } else {
                addBaseLine();
            }
            customerBehaviorAdapter.setData(data);
        }
    }

    @Override
    public void onFailure(String url, String error) {

    }

    private void dismissLoading() {

        if (srl != null && srl.isRefreshing()) {
            srl.setRefreshing(false);
        }

    }

    private void removeLoadingItem() {
        if (data.size() > 0) {
            if (data.get(data.size() - 1).getMyType() == 1) {
                data.remove(data.size() - 1);
            }
        }
    }

    private void addBaseLine() {
        if (pageNo != 1) {
            data.add(new VipsMemberActions.BodyBean.ListBean(2));
        }
    }
}
